package com.bit.web;

//UDP服务器

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPEchoServer {
    //对于一个服务器来说，有两部核心操作
    //1.初始化
    //2.主循环，接收并处理请求：
    //  a.读取数据并解析
    //  b.根据请求计算响应
    //  c.把相应结果写会客户端

    private DatagramSocket socket = null;

    public UDPEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //a.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            //收到请求
            socket.receive(requestPacket);

            String request = new String(requestPacket.getData(),
                    0,requestPacket.getLength()).trim();
            //b.根据请求计算响应
            String response = process(request);
            //c.把响应写回客户端，响应数据就是response，需要包装成一个Packet对象
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(requestPacket);

            //此处打印一个日志，用于观察
            System.out.printf("[%s:%d] req: %s;resp: %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }
    public String process(String request){
        //由于此处是一个echo server，请求内容是啥，响应内容就是啥
        return request;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoServer server = new UDPEchoServer(9090);
        server.start();
    }
}
